package com.bdqn.ch02.JD.jd3;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * XMLDelete
 *
 *   使用DOM 进行对文档的删除
 *   @aurhor Administrator  whs
 *   @since 2024/7/1
 *  */
public class XMLDelete {

    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse("src/com/bdqn/ch02/JD/成绩信息.xml");

            NodeList list = doc.getElementsByTagName("student");
            for (int i = 0; i < list.getLength(); i++) {
                Element studentEle = (Element) list.item(i);
                String studentId = studentEle.getAttribute("id");
                if(studentId.equals("1")){
                    studentEle.getParentNode().removeChild(studentEle);
                }
            }

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transform = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(doc);

            transform.setOutputProperty(OutputKeys.ENCODING, "gb2312");
            StreamResult result = new StreamResult(new FileOutputStream("src/com/bdqn/ch02/JD/成绩信息.xml"));
            System.out.println("删除成功！");
            transform.transform(domSource, result);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

